package com.cn.delan.web.mvc.admin.action;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;

import com.cn.delan.core.util.StringUtil;
import com.cn.delan.web.mvc.admin.AdminConst;
import com.cn.delan.web.mvc.admin.bean.UserBean;
import com.cn.delan.web.mvc.admin.service.IUserService;
import com.cn.delan.web.mvc.core.action.AbstractAction;
/**
 * 登录
 * @author BingGo
 *
 */
public class LoginAction extends AbstractAction {
	private IUserService<UserBean> userService;

	public IUserService<UserBean> getUserService() {
		return userService;
	}

	public void setUserService(IUserService<UserBean> userService) {
		this.userService = userService;
	}

	@Override
	public ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String userName = this.getParameter(AdminConst.REQUEST_PARA_USERNAME);
		String password = this.getParameter(AdminConst.REQUEST_PARA_PASSWORD);
		HttpSession session = request.getSession();
		//已登录直接进入登录成功页面
		if(this.isLogin(session)){
			return this.getView(SUCCESS);
		}
		if(!StringUtil.isEmpty(userName)){
			if(!this.checkRandCode(session)){
				//设置校验失败消息
				request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_VALIDFAIL));
				return this.getView(FAIL);
			}
			UserBean user = (UserBean)this.userService.findByUserId(userName);
			if(user!=null){
				if(password!=null && user.getPassword()!=null && password.equals(user.getPassword())){
					//登录绑定
					this.login(session, user);
					return this.getRedirectView(REDIRECT);
				}else{
					//设置密码错误消息
					request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_LOGINFAIL));
					return this.getView(FAIL);
				}
			}else{
				//设置登录失败消息
				request.setAttribute(AdminConst.REQUEST_ATTR_MESSAGE, this.getMessage(AdminConst.MESSAGE_LOGINFAIL));
				return this.getView(FAIL);
			}
		}else{
			return this.getView(INPUT);
		}
	}

}
